local chongjuan = fk.CreateSkill{
    name = "xiaobai__chongjuan",
}
Fk:loadTranslationTable{
    ["xiaobai__chongjuan"] = "宠眷",
    [":xiaobai__chongjuan"] = "摸牌阶段或弃牌阶段结束时，手牌数唯一最多的男性角色可以令你将手牌数摸至比其少一张（至多摸5张），其选择前，你可以先令其摸一张牌。",
    ["#xiaobai__chongjuan1"] = "先给 %dest 摸一张牌，再询问",
    ["#xiaobai__chongjuan2"] = "%dest 不是我喜欢的人，不给摸",
    ["#xiaobai__chongjuan"] = "宠眷：正在询问 %dest 是否令你将手牌数摸至比其少一张",
    ["#xiaobai__chongjuan-choose"] = "宠眷：是否令 %dest 将手牌摸至比你少一张",
}

chongjuan:addEffect(fk.EventPhaseEnd, {
    can_trigger = function (self, event, target, player, data)
        if player:hasSkill(chongjuan.name) and target == player and table.contains({Player.Draw, Player.Discard}, player.phase) then
            local room = player.room
            local targets = table.filter(room.alive_players, function (cp)
                return cp:isMale()
            end)
            local current = table.find(targets, function (cp)
                return table.every(targets, function (tp)
                    return cp == tp or cp:getHandcardNum() > tp:getHandcardNum()
                end) and cp:getHandcardNum() > player:getHandcardNum()
            end)
            p(table.map(targets, function (element, index, array)
                return element.general
            end))
            if current then
                p(current.general)
                event:setCostData(self, current)
                return true
            end
        end
    end,
    on_cost = function (self, event, target, player, data)
        local current = event:getCostData(self)
        local choice = player.room:askToChoice(player, {
            choices = {"#xiaobai__chongjuan1::"..current.id,"#xiaobai__chongjuan2::"..current.id},
            skill_name = chongjuan.name,
            prompt = "#xiaobai__chongjuan::"..current.id
        })
        local anim_type = "special"
        if choice:startsWith("#xiaobai__chongjuan1") then
            anim_type = "drawcard"
        end
        event:setCostData(self, {to = current, choice = choice, anim_type = anim_type})
        return true
    end,
    on_use = function (self, event, target, player, data)
        local room = player.room
        local current = event:getCostData(self).to
        local choice = event:getCostData(self).choice
        if choice:startsWith("#xiaobai__chongjuan1") then
            current:drawCards(1, chongjuan.name)
        end
        if room:askToSkillInvoke(current, {
            skill_name = chongjuan.name,
            prompt = "#xiaobai__chongjuan-choose::"..player.id
        }) then
            local num = math.min(current:getHandcardNum() - 1 - player:getHandcardNum(), 5)
            if num > 0 then
                player:drawCards(num, chongjuan.name)
            end
        end
    end,
})

return chongjuan